package com.atguigu.ssyx.product.config;

import com.atguigu.ssyx.model.product.QiniuInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.util.Auth;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.Configuration;
import org.redisson.misc.Hash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class QiniuService {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    public Map uploadFile(MultipartFile file) throws IOException {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        Configuration cfg = new Configuration();
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            byte[] byteData = file.getBytes();
            String UUIDName = UUID.randomUUID().toString().replace("-", "");
            String Filename = UUIDName + "-" + file.getOriginalFilename();

            System.out.println(file);

            Response response = uploadManager.put(byteData, Filename, upToken);
            // 解析上传成功的结果
            String responseBody = response.bodyString();


            ObjectMapper objectMapper = new ObjectMapper();
            QiniuInfo qiniuInfo = objectMapper.readValue(responseBody, QiniuInfo.class);
            String key = qiniuInfo.getKey();
            System.out.println(key);
//            responseBody.
            String fileUrl = "http://" + domain + "/" + key;
            // 可以根据需要解析返回的 JSON 字符串获取文件的 URL 等信息
            Map map = new HashMap();
            map.put("fileName", key);
            map.put("fileUrl", fileUrl);

            return map;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
